package com.hl.card.modular.packBack.controller;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.constant.factory.PageFactory;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.model.CreditCard;
import com.hl.card.common.util.DateUtils;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.packBack.service.CreditCardService;


@Controller
@RequestMapping("/creditCard")
public class CreditCardController extends BaseController{

	@Autowired
	private CreditCardService creditCardService;

	private String PREFIX = "/packback/credit_card/";
	
	
	/**
	 * 跳转列表
	 * 
	 * @return
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "credit_card.html";
	}

	@RequestMapping("/excelList")
	public String excelList() {
		return PREFIX + "credit_card_add.html";
	}

	
	
	/**
	 * 导入
	 * @param upfile
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadExcel")
	@ResponseBody
	public Object uploadExcel(MultipartFile upfile, HttpServletRequest request)throws Exception{
		// 创建Excel工作薄
		if (upfile == null) {
			return super.FailuerTip("请选择上传的excel文件！");
		}
		Workbook work = getWorkbook(upfile.getInputStream());
		if (null == work) {
			return super.FailuerTip("Excel工作薄不能为空！");
		}
		Sheet sheet = null;
		Row row = null;
		sheet = work.getSheetAt(0);
		if (sheet == null) {
			return super.FailuerTip("Excel的Shell不能为空！");
		}
		Integer id = ShiroKit.getUser().getId();
		request.getSession().setAttribute("upload_total_count" + id,sheet.getLastRowNum());
		List<CreditCard> dataList=new ArrayList<CreditCard>();
		// 遍历当前sheet中的所有行
		for (int j = 1; j <= sheet.getLastRowNum(); j++) {
			row = sheet.getRow(j);
			if (row == null) {
				continue;
			}
			CreditCard data=new CreditCard();
			data.setM_code(getCellValue(row.getCell(0)));
			data.setCustomer_name(getCellValue(row.getCell(1)));
			data.setPhone(getCellValue(row.getCell(2)));
			data.setExamine_time(DateUtils.strToDate(getCellValue(row.getCell(3))));
			data.setCard_level(getCellValue(row.getCell(4)).equals("白金")?0:1);
			data.setCard_product(getCellValue(row.getCell(5)));
			data.setIs_new(getCellValue(row.getCell(6)).equals("否")?0:1);
			data.setIs_active(getCellValue(row.getCell(7)).equals("否")?0:1);
			String card_status=getCellValue(row.getCell(8));
			Integer card_status_num=0;
			if(card_status.equals("待激活"))
			{
				card_status_num=0;
			}else if(card_status.equals("正常"))
			{
				card_status_num=1;
			}else if(card_status.equals("销卡"))
			{
				card_status_num=2;
			}
			data.setCard_status(card_status_num);
			data.setCustomer_status(getCellValue(row.getCell(9)).equals("空白")||getCellValue(row.getCell(9)).equals("")?0:1);
			data.setActivation_time(DateUtils.strToDate(getCellValue(row.getCell(10))));
			data.setConsume_time(DateUtils.strToDate(getCellValue(row.getCell(11))));
			data.setLive_consume_time(DateUtils.strToDate(getCellValue(row.getCell(12))));
			data.setTrack_code(getCellValue(row.getCell(13)));
			data.setApply_no(getCellValue(row.getCell(14)));
			data.setAdd_time(DateUtils.strToDate(getCellValue(row.getCell(15))));
			dataList.add(data);
		}
		Map<String,Object> data=creditCardService.uploadExcel(dataList,request);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 200);
		result.put("data", data);
		result.put("message", "操作成功!");
		return result;
	}

	/**
	 *
	 * @param inStr
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr) throws Exception {
		Workbook wb = null;
		wb = WorkbookFactory.create(inStr);
		return wb;
	}

	private String getCellValue(Cell cell) {
		String result = new String();
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
			if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
				SimpleDateFormat sdf = null;
				if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
						.getBuiltinFormat("h:mm")) {
					sdf = new SimpleDateFormat("HH:mm");
				} else {// 日期
					sdf = new SimpleDateFormat("yyyy-MM-dd");
				}
				Date date = cell.getDateCellValue();
				result = sdf.format(date);
			} else if (cell.getCellStyle().getDataFormat() == 58) {
				// 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				double value = cell.getNumericCellValue();
				Date date = org.apache.poi.ss.usermodel.DateUtil
						.getJavaDate(value);
				result = sdf.format(date);
			} else {
				double value = cell.getNumericCellValue();
				CellStyle style = cell.getCellStyle();
				DecimalFormat format = new DecimalFormat();
				String temp = style.getDataFormatString();
				// 单元格设置成常规
				if (temp.equals("General")) {
					format.applyPattern("#");
				}
				result = format.format(value);
			}
			break;
		case HSSFCell.CELL_TYPE_STRING:// String类型
			result = cell.getRichStringCellValue().toString();
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			result = "";
		default:
			result = "";
			break;
		}
		return result;
	}

	
	@RequestMapping("/getUploadCount")
	@ResponseBody
	public Object getUploadCount(HttpServletRequest request) {
		Integer id = ShiroKit.getUser().getId();
		Integer count = request.getSession().getAttribute("upload_count" + id) == null ? 0: (Integer) request.getSession().getAttribute("upload_count" + id);
		Integer total_count = request.getSession().getAttribute("upload_total_count" + id) == null ? 0 : (Integer) request.getSession().getAttribute("upload_total_count" + id);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("count", count);
		data.put("total_count", total_count);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 200);
		result.put("message", "操作成功");
		result.put("data", data);
		return result;
	}

	
	/**
	 * 查询列表
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Object list(CreditCard card, HttpServletRequest request) {
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		Page<CreditCard> page = new PageFactory<CreditCard>().defaultPage();
		List<CreditCard> list = creditCardService.list(page, card, sort,order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("rows", list);
		result.put("total", page.getTotal());
		return result;
	}
}
